//
//  SCIMUploadManager.m
//  Shuaiche
//
//  Created by xiangtao on 2024/12/19.
//  Copyright © 2024 ShuaiChe. All rights reserved.
//

#import "SCIMUploadManager.h"
#import <AliyunOSSiOS/OSSService.h>
#import <AliyunOSSiOS/OSSCompat.h>
#import "SCHttpManager.h"
#import "MBProgressHUD+Add.h"
#import "NSString+Helper.h"
#import <Photos/Photos.h>
#import "SCNetworkStatusConst.h"
#import "SCAppConfig.h"

static NSString *const endPoint = @"https://oss-cn-hangzhou.aliyuncs.com";
static NSString *const bucketName = @"scim";
static NSString *const kAccessKeyId = @"accessKeyId";
static NSString *const kAccessKeySecret = @"accessKeySecret";
static NSString *const kSecurityToken = @"securityToken";
static NSString *const kExpiration = @"expiration";
static NSString *const kDomain = @"https://scim.shuaiche.com/";

@interface SCIMUploadManager ()
@property (strong, nonatomic) dispatch_group_t uploadImageGroup;
@end

@implementation SCIMUploadManager
+ (instancetype)sharedInstance {
    static SCIMUploadManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[SCIMUploadManager alloc] init];
        manager.uploadImageGroup = dispatch_group_create();
    });
    return manager;
}

#pragma -mark- 上传图片
+ (void)startUploadImage:(UIImage *)image completion:(void(^)(NSString *picUrl, NSString *fileName, NSString *errorString))block {
    
    NSString *datePath = [self getIMPathPre:OSSTypeMedia];
    WEAKSELF
    [[SCHttpManager shareInstance] httpGet:[self uploadUrl] param:nil completion:^(NSDictionary *responseJson, NSError *error) {
        if (error) {
            if (block) {
                block(nil,nil,error.localizedDescription);
            }
        } else {
            STRONGSELF
            if(!strongSelf){
                Return_From_Block
            }
            id<OSSCredentialProvider> credential = [[OSSFederationCredentialProvider alloc] initWithFederationTokenGetter:^OSSFederationToken * {
                OSSFederationToken * token = [OSSFederationToken new];
                token.tAccessKey = responseJson[kAccessKeyId];
                token.tSecretKey = responseJson[kAccessKeySecret];
                token.tToken = responseJson[kSecurityToken];
                token.expirationTimeInGMTFormat = responseJson[kExpiration];
                return token;
            }];
            OSSClient *client = [[OSSClient alloc] initWithEndpoint:endPoint credentialProvider:credential];
            
          NSString *name = [[[NSString UUIDString] stringByReplacingOccurrencesOfString:@"-" withString:@""] stringByAppendingString:@".jpeg"];;

            NSString *objectKey = [NSString stringWithFormat:@"%@/%@",datePath,name];
            NSLog(@"objectKey = %@",objectKey);

            
            OSSPutObjectRequest * putRequest = [OSSPutObjectRequest new];
            putRequest.objectKey = objectKey;
            putRequest.uploadingData = UIImageJPEGRepresentation(image, 0.7);
            putRequest.bucketName = bucketName;
            putRequest.cacheControl = @"max-age=31104000";
            OSSTask * task = [client putObject:putRequest];
            [task continueWithBlock:^id(OSSTask *task) {
                //OSSPutObjectResult * result = task.result;
                if (!task.error) {
                    if(!strongSelf){
                        return nil;
                    }
                                        
                    NSString *imageUrl = [NSString stringWithFormat:@"%@%@",kDomain,objectKey];
                    NSLog(@"Put image success!, %@",imageUrl);
                    block(imageUrl, name, nil);
                                      
                } else {
                    NSLog(@"Put image failed, %@", task.error);
                    if(!strongSelf){
                        return nil;
                    }
                    if (task.error.code == OSSClientErrorCodeTaskCancelled) {
                    } else {
                    }
                }
                return nil;
            }];
          // 等待任务完成。
          [task waitUntilFinished];
            
        }
    }];
}

//上传视频
+ (void)startUploadVideo:(NSData *)data completion:(void(^)(NSString *videoUrl,NSString *errorString))block {
    NSString *datePath = [self getIMPathPre:OSSTypeMedia];
    WEAKSELF
    [[SCHttpManager shareInstance] httpGet:[self uploadUrl] param:nil completion:^(NSDictionary *responseJson, NSError *error) {
        if (error) {
            if (block) {
                block(nil,error.localizedDescription);
            }
        } else {
            STRONGSELF
            if(!strongSelf){
                Return_From_Block
            }
            id<OSSCredentialProvider> credential = [[OSSFederationCredentialProvider alloc] initWithFederationTokenGetter:^OSSFederationToken * {
                OSSFederationToken * token = [OSSFederationToken new];
                token.tAccessKey = responseJson[kAccessKeyId];
                token.tSecretKey = responseJson[kAccessKeySecret];
                token.tToken = responseJson[kSecurityToken];
                token.expirationTimeInGMTFormat = responseJson[kExpiration];
                return token;
            }];
            OSSClient *client = [[OSSClient alloc] initWithEndpoint:endPoint credentialProvider:credential];
            
            NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0];
            NSString *timeSp = [NSString stringWithFormat:@"%f", [date timeIntervalSince1970]];
            int random = (arc4random() % 90001) + 10000;
            NSString *name = [NSString stringWithFormat:@"%@.mp4",[CoolUtil md5ForString:[NSString stringWithFormat:@"%@%d",timeSp,random]]];

            NSString *objectKey = [NSString stringWithFormat:@"%@/%@",datePath,name];
            NSLog(@"objectKey = %@",objectKey);

            
            OSSPutObjectRequest * putRequest = [OSSPutObjectRequest new];
            putRequest.objectKey = objectKey;
            putRequest.uploadingData = data;
            putRequest.bucketName = bucketName;
            putRequest.cacheControl = @"max-age=31104000";
            OSSTask * task = [client putObject:putRequest];
            [task continueWithBlock:^id(OSSTask *task) {
                //OSSPutObjectResult * result = task.result;
                if (!task.error) {
                    if(!strongSelf){
                        return nil;
                    }
                                        
                    NSString *videoUrl = [NSString stringWithFormat:@"%@%@",kDomain,objectKey];
                    NSLog(@"Put video success!, %@",videoUrl);
                    block(videoUrl,nil);
                                      
                } else {
                    NSLog(@"Put video failed, %@", task.error);
                    if(!strongSelf){
                        return nil;
                    }
                    if (task.error.code == OSSClientErrorCodeTaskCancelled) {
                    } else {
                    }
                }
                return nil;
            }];
          // 等待任务完成。
          [task waitUntilFinished];
            
        }
    }];
}

//上传语音
+ (void)startUploadVoice:(NSData *)data completion:(void(^)(NSString *voiceUrl,NSString *errorString))block {
    NSLog(@"data.length = %ld",data.length);
    NSString *datePath = [self getIMPathPre:OSSTypeSound];
    WEAKSELF
    //[MBProgressHUD showMessage:Network_Request_Loading toView:self.view];
    [[SCHttpManager shareInstance] httpGet:[self uploadUrl] param:nil completion:^(NSDictionary *responseJson, NSError *error) {
        if (error) {
            if (block) {
                block(nil,error.localizedDescription);
            }
        } else {
            STRONGSELF
            if(!strongSelf){
                Return_From_Block
            }
            id<OSSCredentialProvider> credential = [[OSSFederationCredentialProvider alloc] initWithFederationTokenGetter:^OSSFederationToken * {
                OSSFederationToken * token = [OSSFederationToken new];
                token.tAccessKey = responseJson[kAccessKeyId];
                token.tSecretKey = responseJson[kAccessKeySecret];
                token.tToken = responseJson[kSecurityToken];
                token.expirationTimeInGMTFormat = responseJson[kExpiration];
                return token;
            }];
            OSSClient *client = [[OSSClient alloc] initWithEndpoint:endPoint credentialProvider:credential];
            
            NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0];
            NSString *timeSp = [NSString stringWithFormat:@"%f", [date timeIntervalSince1970]];
            int random = (arc4random() % 90001) + 10000;
            NSString *name = [NSString stringWithFormat:@"%@.mp3",[CoolUtil md5ForString:[NSString stringWithFormat:@"%@%d",timeSp,random]]];

            NSString *objectKey = [NSString stringWithFormat:@"%@/%@",datePath,name];
            NSLog(@"objectKey = %@",objectKey);

            
            OSSPutObjectRequest * putRequest = [OSSPutObjectRequest new];
            //putRequest.objectKey = [NSString stringWithFormat:@"img/license/%@",[filePath lastPathComponent]];
            // putRequest.uploadingFileURL = [NSURL fileURLWithPath:filePath];
            
            putRequest.objectKey = objectKey;
            putRequest.uploadingData = data;
            putRequest.bucketName = bucketName;
            putRequest.cacheControl = @"max-age=31104000";
            OSSTask * task = [client putObject:putRequest];
            [task continueWithBlock:^id(OSSTask *task) {
                //OSSPutObjectResult * result = task.result;
                if (!task.error) {
                    if(!strongSelf){
                        return nil;
                    }
                    
                    NSString *voiceUrl = [NSString stringWithFormat:@"%@%@",kDomain,objectKey];
                    block(voiceUrl,nil);
                    NSLog(@"Put voice success!, %@",voiceUrl);
                    
                } else {
                    NSLog(@"Put voice failed, %@", task.error);
                    if(!strongSelf){
                        return nil;
                    }
                    if (task.error.code == OSSClientErrorCodeTaskCancelled) {
                    } else {
                    }
                }
                return nil;
            }];
          // 等待任务完成。
          [task waitUntilFinished];
            
        }
    }];
}

//上传文件
+ (void)startUploadFile:(NSData *)data fileName:(NSString *)fileName completion:(void(^)(NSString *fileUrl,NSString *errorString))block {
    NSLog(@"data.length = %ld",data.length);
    NSString *datePath = [self getIMPathPre:OSSTypeFile];
    WEAKSELF
    //[MBProgressHUD showMessage:Network_Request_Loading toView:self.view];
    [[SCHttpManager shareInstance] httpGet:[self uploadUrl] param:nil completion:^(NSDictionary *responseJson, NSError *error) {
        if (error) {
            if (block) {
                block(nil,error.localizedDescription);
            }
        } else {
            STRONGSELF
            if(!strongSelf){
                Return_From_Block
            }
            id<OSSCredentialProvider> credential = [[OSSFederationCredentialProvider alloc] initWithFederationTokenGetter:^OSSFederationToken * {
                OSSFederationToken * token = [OSSFederationToken new];
                token.tAccessKey = responseJson[kAccessKeyId];
                token.tSecretKey = responseJson[kAccessKeySecret];
                token.tToken = responseJson[kSecurityToken];
                token.expirationTimeInGMTFormat = responseJson[kExpiration];
                return token;
            }];
            OSSClient *client = [[OSSClient alloc] initWithEndpoint:endPoint credentialProvider:credential];
            
            NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0];
            NSString *timeSp = [NSString stringWithFormat:@"%f", [date timeIntervalSince1970]];
            int random = (arc4random() % 90001) + 10000;
            NSString *suffix = [fileName componentsSeparatedByString:@"."].lastObject;
            NSString *name = [NSString stringWithFormat:@"%@.%@",[CoolUtil md5ForString:[NSString stringWithFormat:@"%@%d",timeSp,random]],suffix];

            NSString *objectKey = [NSString stringWithFormat:@"%@/%@",datePath,name];
            NSLog(@"objectKey = %@",objectKey);

            OSSPutObjectRequest * putRequest = [OSSPutObjectRequest new];
            //putRequest.objectKey = [NSString stringWithFormat:@"img/license/%@",[filePath lastPathComponent]];
            // putRequest.uploadingFileURL = [NSURL fileURLWithPath:filePath];
            
            putRequest.objectKey = objectKey;
            putRequest.uploadingData = data;
            putRequest.bucketName = bucketName;
            putRequest.cacheControl = @"max-age=31104000";
            OSSTask * task = [client putObject:putRequest];
            [task continueWithBlock:^id(OSSTask *task) {
                //OSSPutObjectResult * result = task.result;
                if (!task.error) {
                    if(!strongSelf){
                        return nil;
                    }
                    
                    NSString *fileUrl = [NSString stringWithFormat:@"%@%@",kDomain,objectKey];
                    block(fileUrl,nil);
                    NSLog(@"Put voice success!, %@",fileUrl);
                    
                } else {
                    NSLog(@"Put voice failed, %@", task.error);
                    if(!strongSelf){
                        return nil;
                    }
                    if (task.error.code == OSSClientErrorCodeTaskCancelled) {
                    } else {
                    }
                }
                return nil;
            }];
          // 等待任务完成。
          [task waitUntilFinished];
            
        }
    }];
}

+ (NSString *)getIMPathPre:(OSSType)ossType{
    NSString * prefix = @"";
#ifdef APP_STORE

#else
    prefix = @"temp/";
#endif
    
    if (ossType == OSSTypeMedia) {
        prefix = [NSString stringWithFormat:@"%@image",prefix];
    } else if (ossType == OSSTypeSound) {
        prefix = [NSString stringWithFormat:@"%@sound",prefix];
    } else if (ossType == OSSTypeFile) {
        prefix = [NSString stringWithFormat:@"%@file",prefix];
    }
    return prefix;
}

+ (NSString *)uploadUrl{
    NSString *uploadUrl = [NSString stringWithFormat:@"%@/baseprod/resource/access",kSC_API_DOMAIN];
    return uploadUrl;
}

@end
